package com.ruoyi.manage.organization.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StrUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.manage.enterprise.domain.SysUserExpand;
import com.ruoyi.manage.enterprise.service.ISysUserExpandService;
import com.ruoyi.manage.organization.domain.OcFinancingMatch;
import com.ruoyi.manage.organization.domain.vo.OcFinancingMatchVo;
import com.ruoyi.manage.organization.service.IOcFinancingMatchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 需求匹配Controller
 *
 * @author ruoyi
 * @date 2025-08-19
 */
@Api(tags = "需求匹配控制器")
@RestController
@RequestMapping("/manage/match")
public class OcFinancingMatchController extends BaseController {
    /**
     * 配置表别名 默认空
     */
    private final static String TABLE_PREFIX = StrUtil.initTableAlias(null);
    @Autowired
    private IOcFinancingMatchService ocFinancingMatchService;

    @Autowired
    private ISysUserExpandService iSysUserExpandService;

    /**
     * 查询需求匹配列表
     */
    @ApiOperation(value = "查询需求匹配", notes = "需求匹配管理")
    @PreAuthorize("@ss.hasPermi('manage:match:list')")
    @GetMapping("/list")
    public TableDataInfo list(OcFinancingMatchVo ocFinancingMatch, QueryWrapper<OcFinancingMatch> queryWrapper) {
        setQueryCondition(ocFinancingMatch, queryWrapper);
        startPage();
        List<OcFinancingMatch> list = ocFinancingMatchService.list(queryWrapper);
        return getDataTable(list);
    }

    @ApiOperation(value = "查询需求匹配", notes = "需求匹配管理")
    @GetMapping("/listByOranization")
    public TableDataInfo listByOranization(OcFinancingMatchVo ocFinancingMatch, QueryWrapper<OcFinancingMatch> queryWrapper) {
        Long userId = SecurityUtils.getUserId();
//        List<SysUserExpand> expandList = iSysUserExpandService.list(new QueryWrapper<SysUserExpand>().eq("user_id", userId).eq("user_type", 1));
        SysUserExpand userExpand = iSysUserExpandService.lambdaQuery().eq(SysUserExpand::getUserId, userId).eq(SysUserExpand::getUserType, 1).one();
        startPage();
        List<OcFinancingMatch> list = ocFinancingMatchService.lambdaQuery().apply("INSTR(org_path, {0}) > 0", userExpand.getDataPermission()).eq(OcFinancingMatch::getState,ocFinancingMatch.getState()).orderByDesc(OcFinancingMatch::getApplyTime).list();
        return getDataTable(list);
    }

    private void setQueryCondition(OcFinancingMatchVo ocFinancingMatch, QueryWrapper<OcFinancingMatch> queryWrapper) {
        if (StrUtil.isNotBlank(ocFinancingMatch.getBachNo())) {
            queryWrapper.eq(TABLE_PREFIX + "bach_no", ocFinancingMatch.getBachNo());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getMachId())) {
            queryWrapper.eq(TABLE_PREFIX + "mach_id", ocFinancingMatch.getMachId());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getApplyId())) {
            queryWrapper.eq(TABLE_PREFIX + "apply_id", ocFinancingMatch.getApplyId());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getMatchType())) {
            queryWrapper.eq(TABLE_PREFIX + "match_type", ocFinancingMatch.getMatchType());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getMatchState())) {
            queryWrapper.eq(TABLE_PREFIX + "match_state", ocFinancingMatch.getMatchState());
        }
        if (ocFinancingMatch.getProductId() != null) {
            queryWrapper.eq(TABLE_PREFIX + "product_id", ocFinancingMatch.getProductId());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getProductName())) {
            queryWrapper.like(TABLE_PREFIX + "product_name", ocFinancingMatch.getProductName());
        }
        if (ocFinancingMatch.getEnterpriseId() != null) {
            queryWrapper.eq(TABLE_PREFIX + "enterprise_id", ocFinancingMatch.getEnterpriseId());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getEnterpriseName())) {
            queryWrapper.like(TABLE_PREFIX + "enterprise_name", ocFinancingMatch.getEnterpriseName());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getCreditCode())) {
            queryWrapper.eq(TABLE_PREFIX + "credit_code", ocFinancingMatch.getCreditCode());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getProvinceSiteId())) {
            queryWrapper.eq(TABLE_PREFIX + "province_site_id", ocFinancingMatch.getProvinceSiteId());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getProvinceName())) {
            queryWrapper.like(TABLE_PREFIX + "province_name", ocFinancingMatch.getProvinceName());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getCitySiteId())) {
            queryWrapper.eq(TABLE_PREFIX + "city_site_id", ocFinancingMatch.getCitySiteId());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getCityName())) {
            queryWrapper.like(TABLE_PREFIX + "city_name", ocFinancingMatch.getCityName());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getAreaSiteId())) {
            queryWrapper.eq(TABLE_PREFIX + "area_site_id", ocFinancingMatch.getAreaSiteId());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getAreaName())) {
            queryWrapper.like(TABLE_PREFIX + "area_name", ocFinancingMatch.getAreaName());
        }
        if (ocFinancingMatch.getDeleted() != null) {
            queryWrapper.eq(TABLE_PREFIX + "deleted", ocFinancingMatch.getDeleted());
        }
        if (ocFinancingMatch.getVersion() != null) {
            queryWrapper.eq(TABLE_PREFIX + "version", ocFinancingMatch.getVersion());
        }
        if (ocFinancingMatch.getApplyTime() != null) {
            queryWrapper.eq(TABLE_PREFIX + "apply_time", ocFinancingMatch.getApplyTime());
        }
        if (ocFinancingMatch.getApplyAmountMin() != null) {
            queryWrapper.eq(TABLE_PREFIX + "apply_amount_min", ocFinancingMatch.getApplyAmountMin());
        }
        if (ocFinancingMatch.getApplyAmountMax() != null) {
            queryWrapper.eq(TABLE_PREFIX + "apply_amount_max", ocFinancingMatch.getApplyAmountMax());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getArrivalTimeType())) {
            queryWrapper.eq(TABLE_PREFIX + "arrival_time_type", ocFinancingMatch.getArrivalTimeType());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getMaturityMin())) {
            queryWrapper.eq(TABLE_PREFIX + "maturity_min", ocFinancingMatch.getMaturityMin());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getMaturityMax())) {
            queryWrapper.eq(TABLE_PREFIX + "maturity_max", ocFinancingMatch.getMaturityMax());
        }
        if (ocFinancingMatch.getRateMax() != null) {
            queryWrapper.eq(TABLE_PREFIX + "rate_max", ocFinancingMatch.getRateMax());
        }
        if (ocFinancingMatch.getRateMin() != null) {
            queryWrapper.eq(TABLE_PREFIX + "rate_min", ocFinancingMatch.getRateMin());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getTaxLevel())) {
            queryWrapper.eq(TABLE_PREFIX + "tax_level", ocFinancingMatch.getTaxLevel());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getDepositBank())) {
            queryWrapper.eq(TABLE_PREFIX + "deposit_bank", ocFinancingMatch.getDepositBank());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getTaxAmount())) {
            queryWrapper.eq(TABLE_PREFIX + "tax_amount", ocFinancingMatch.getTaxAmount());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getIncomeData())) {
            queryWrapper.eq(TABLE_PREFIX + "income_data", ocFinancingMatch.getIncomeData());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getProfitState())) {
            queryWrapper.eq(TABLE_PREFIX + "profit_state", ocFinancingMatch.getProfitState());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getCollateralFlag())) {
            queryWrapper.eq(TABLE_PREFIX + "collateral_flag", ocFinancingMatch.getCollateralFlag());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getLoanBankName())) {
            queryWrapper.like(TABLE_PREFIX + "loan_bank_name", ocFinancingMatch.getLoanBankName());
        }
        if (ocFinancingMatch.getLoanLeftAmount() != null) {
            queryWrapper.eq(TABLE_PREFIX + "loan_left_amount", ocFinancingMatch.getLoanLeftAmount());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getGuaranteeType())) {
            queryWrapper.eq(TABLE_PREFIX + "guarantee_type", ocFinancingMatch.getGuaranteeType());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getRepaymentType())) {
            queryWrapper.eq(TABLE_PREFIX + "repayment_type", ocFinancingMatch.getRepaymentType());
        }
        if (ocFinancingMatch.getAmountLimitLower() != null) {
            queryWrapper.eq(TABLE_PREFIX + "amount_limit_lower", ocFinancingMatch.getAmountLimitLower());
        }
        if (ocFinancingMatch.getAmountLimitUpper() != null) {
            queryWrapper.eq(TABLE_PREFIX + "amount_limit_upper", ocFinancingMatch.getAmountLimitUpper());
        }
        if (ocFinancingMatch.getInterestRateLimitLower() != null) {
            queryWrapper.eq(TABLE_PREFIX + "interest_rate_limit_lower", ocFinancingMatch.getInterestRateLimitLower());
        }
        if (ocFinancingMatch.getInterestRateLimitUpper() != null) {
            queryWrapper.eq(TABLE_PREFIX + "interest_rate_limit_upper", ocFinancingMatch.getInterestRateLimitUpper());
        }
        if (ocFinancingMatch.getLoanPeriodLimitLower() != null) {
            queryWrapper.eq(TABLE_PREFIX + "loan_period_limit_lower", ocFinancingMatch.getLoanPeriodLimitLower());
        }
        if (ocFinancingMatch.getLoanPeriodLimitUpper() != null) {
            queryWrapper.eq(TABLE_PREFIX + "loan_period_limit_upper", ocFinancingMatch.getLoanPeriodLimitUpper());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getMainGuaranteeWay())) {
            queryWrapper.eq(TABLE_PREFIX + "main_guarantee_way", ocFinancingMatch.getMainGuaranteeWay());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getSecondGuaranteeWay())) {
            queryWrapper.eq(TABLE_PREFIX + "second_guarantee_way", ocFinancingMatch.getSecondGuaranteeWay());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getProductFeature())) {
            queryWrapper.eq(TABLE_PREFIX + "product_feature", ocFinancingMatch.getProductFeature());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getRepaymentWay())) {
            queryWrapper.eq(TABLE_PREFIX + "repayment_way", ocFinancingMatch.getRepaymentWay());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getProductLogo())) {
            queryWrapper.eq(TABLE_PREFIX + "product_logo", ocFinancingMatch.getProductLogo());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getOrgPath())) {
            queryWrapper.eq(TABLE_PREFIX + "org_path", ocFinancingMatch.getOrgPath());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getCoveragePath())) {
            queryWrapper.eq(TABLE_PREFIX + "coverage_path", ocFinancingMatch.getCoveragePath());
        }
        if (ocFinancingMatch.getExpiredTime() != null) {
            queryWrapper.eq(TABLE_PREFIX + "expired_time", ocFinancingMatch.getExpiredTime());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getFinancialAdvisor())) {
            queryWrapper.eq(TABLE_PREFIX + "financial_advisor", ocFinancingMatch.getFinancialAdvisor());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getSiteId())) {
            queryWrapper.eq(TABLE_PREFIX + "site_id", ocFinancingMatch.getSiteId());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getSiteCode())) {
            queryWrapper.eq(TABLE_PREFIX + "site_code", ocFinancingMatch.getSiteCode());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getSiteName())) {
            queryWrapper.like(TABLE_PREFIX + "site_name", ocFinancingMatch.getSiteName());
        }
        if (StrUtil.isNotBlank(ocFinancingMatch.getTicketId())) {
            queryWrapper.eq(TABLE_PREFIX + "ticket_id", ocFinancingMatch.getTicketId());
        }
        queryWrapper.orderByDesc(TABLE_PREFIX + "create_time");
    }

    /**
     * 导出需求匹配列表
     */
    @PreAuthorize("@ss.hasPermi('manage:match:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, OcFinancingMatchVo ocFinancingMatch, QueryWrapper<OcFinancingMatch> queryWrapper) {
        if (CollUtil.isEmpty(ocFinancingMatch.getIds())) {
            setQueryCondition(ocFinancingMatch, queryWrapper);
        } else {
            queryWrapper.in(TABLE_PREFIX + "id", ocFinancingMatch.getIds());
        }
        List<OcFinancingMatch> list = ocFinancingMatchService.list(queryWrapper);
        ExcelUtil<OcFinancingMatch> util = new ExcelUtil<OcFinancingMatch>(OcFinancingMatch.class);
        util.exportExcel(response, list, "match");
    }

    /**
     * 获取需求匹配详细信息
     */
    @ApiOperation(value = "获取需求匹配", notes = "需求匹配管理")
    @PreAuthorize("@ss.hasPermi('manage:match:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(ocFinancingMatchService.queryGetById(id));
    }

    /**
     * 新增需求匹配
     */
    @ApiOperation(value = "新增需求匹配", notes = "需求匹配管理")
    @PreAuthorize("@ss.hasPermi('manage:match:add')")
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@Validated @RequestBody OcFinancingMatch ocFinancingMatch) {
        return toAjax(ocFinancingMatchService.addOcFinancingMatch(ocFinancingMatch) ? 1 : 0);
    }

    /**
     * 修改需求匹配
     */
    @ApiOperation(value = "修改需求匹配", notes = "需求匹配管理")
    @PreAuthorize("@ss.hasPermi('manage:match:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody OcFinancingMatch ocFinancingMatch) {
        return toAjax(ocFinancingMatchService.updateOcFinancingMatch(ocFinancingMatch) ? 1 : 0);
    }

    /**
     * 删除需求匹配
     */
    @ApiOperation(value = "删除需求匹配", notes = "需求匹配管理")
    @PreAuthorize("@ss.hasPermi('manage:match:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ocFinancingMatchService.deleteOcFinancingMatchByIds(ids) ? 1 : 0);
    }
}
